import { plugin, Messagetype } from 'alemon'
import { Mint } from 'mint-filter'
import { sync } from 'glob'
import { readFileSync } from 'fs'
import { join } from 'node:path'
import { MyDirPath } from '../../app.config.js'

let mint: Mint
export class K_敏感词 extends plugin {
  constructor() {
    super({
      dsc: '插件描述',
      priority: 10,
      rule: [
        {
          reg: /(.*)/,
          fnc: '敏感词'
        }
      ]
    })

    const txtList = sync(join(MyDirPath, '/resources/*.txt'), {
      windowsPathsNoEscape: true
    })

    let txt = ''
    txtList.forEach(item => {
      txt += readFileSync(item, { encoding: 'utf-8' }) + '\n'
    })

    const lines = txt.replace(/\r/g, '').replace(/,/g, '').split('\n')
    const filteredArr = lines.filter(item => item.trim() !== '') // 过滤掉空字符串

    mint = new Mint(filteredArr)
  }
  async 敏感词(e: Messagetype) {
    //    需要私域或公域事件
    if ((e.eventType !== 'CREATE' && e.event !== 'MESSAGES') || e.isGroup) {
      return
    }

    if (e.cmd_msg && !mint.verify(e.cmd_msg)) {
      //  撤回消息
      client.messageApi
        .deleteMessage(e.msg.channel_id, e.msg.id, false)
        .then(() => {
          // 禁言
          client.muteApi
            .muteMember(e.msg.guild_id, e.msg.author.id, {
              seconds: 10 * 60 + '' // 10分钟
            })
            .then(async () => {
              return e.reply(`<@!${e.msg.author.id}> 请文明用语`)
            })
        })
        .catch(async () => {
          return e.reply(`<@!${e.msg.author.id}> 虽然禁不了你，但请文明用语`)
        })
    }

    return false
  }
}
